package net.dgg.rz.production.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.dgg.framework.tac.utils.idutil.DggKeyWorker;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.systemRecord.entity.SystemRecord;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.dao.NodeTimeOutPunishDao;
import net.dgg.rz.production.dao.PunishDetailDao;
import net.dgg.rz.production.dao.PunishSchemeDao;
import net.dgg.rz.production.entity.NodeTimeOutPunish;
import net.dgg.rz.production.entity.ProductOrder;
import net.dgg.rz.production.entity.PunishDetail;
import net.dgg.rz.production.entity.PunishScheme;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationEntity;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 扣罚方案 service层
 * Created by cuipeng on 2019/03/19.
 **/
@Service
public class PunishSchemeService extends BaseService{
    @Autowired
    private PunishSchemeDao punishSchemeDao;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private PunishDetailDao punishDetailDao;
    @Autowired
    private SystemRecordService systemRecordService;
    @Autowired
    private TranslateUtil translateUtil;
    @Resource
    private NodeTimeOutPunishDao nodeTimeOutPunishDao;
    /**
     * @Title: 查询扣罚方案数据
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    public List<PunishScheme> queryPunishList(Map map){
        return punishSchemeDao.queryWithPage(map);
    }
    /**
     * @Title: 查询扣罚方案数据
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    public List<Map> searchAllPunishDetail(Map map){
        return punishDetailDao.selectPunishDetailByPunishId(map);
    }
    /**
     * @Title: 新增扣罚方案
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    @Transactional
    public void addPunish(Map map){
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map.get("punishName"), ProductOrderExcption.class, "方案名称不能为空！");
        ValidateUtils.isTrue(String.valueOf(map.get("punishName")).length()<=10,ProductOrderExcption.class,"方案名称不能超过10个字！");
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(sessionUser.getOrgId());
        ValidateUtils.strNotEmpty(org, ProductOrderExcption.class, "未获取到登录人部门信息！");
        PunishScheme punishScheme = new PunishScheme();
        Long punishId = DggKeyWorker.nextId();
        punishScheme.setId(punishId);
        punishScheme.setBusinessTypeCode(ScProductConstant.BUS_YT_DK);
        punishScheme.setBusinessTypeName(ScProductConstant.BUS_YT_DK_NAME);
        //查看方案名称是否存在
        int count = punishSchemeDao.countPunishByName(new HashMap(){{
                        put("businessTypeCode",ScProductConstant.BUS_YT_DK);
                        put("name",map.get("punishName"));
                    }});
        if(count != 0){
            throw new ProductOrderExcption("方案名称不能重复！");
        }
        punishScheme.setName(map.get("punishName").toString().trim());
        if( StringUtils.isNotEmpty(map.get("introduce"))){
            ValidateUtils.isTrue(String.valueOf(map.get("introduce")).length()<=50,ProductOrderExcption.class,"方案介绍不能超过50个字！");
            punishScheme.setIntroduce(map.get("introduce").toString().trim());
        }
        punishScheme.setState(0);//0初始状态 (0:未上架1:已上架2:删除)
        this.saveOpt(punishScheme,sessionUser);
        punishScheme.setCreaterOrgName(org.getName());
        punishScheme.setUpdaterOrgName(org.getName());
        punishSchemeDao.addPunish(punishScheme);
        //添加扣罚方案明细的固定信息
        //新增扣罚方案的时候会固定增加一个扣罚方案明细
        BigDecimal b = new BigDecimal(0);
        PunishDetail punishDetailc = new PunishDetail();
        punishDetailc.setId(DggKeyWorker.nextId());
        punishDetailc.setPunishId(punishId);
        punishDetailc.setFlag(1);
        punishDetailc.setTeamName("全部");
        punishDetailc.setMoney(b);//操行分
        punishDetailc.setConductPoints(b);//罚款
        punishDetailc.setIsBasics(0);
        punishDetailc.setVersion(0L);
        this.saveOpt(punishDetailc,sessionUser);
        punishDetailc.setUpdaterOrgName(org.getName());
        punishDetailc.setCreaterOrgName(org.getName());
        punishDetailDao.addPunishDetail(punishDetailc);
    }
    /**
     * @Title: 修改扣罚方案
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    @Transactional
    public void UpdatePunish(Map map){
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        ValidateUtils.strNotEmpty(map.get("id"), ProductOrderExcption.class, "方案ID不能为空！");
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(sessionUser.getOrgId());
        ValidateUtils.strNotEmpty(org, ProductOrderExcption.class, "未获取到登录人部门信息！");
        Long id = Long.parseLong(map.get("id").toString());
        PunishScheme checkPun = punishSchemeDao.selectPunishById(id);
        ValidateUtils.strNotEmpty(checkPun, ProductOrderExcption.class, "为获取到相应的扣罚方案信息！");
        if(StringUtils.isNotEmpty(map.get("oldState"))){
            if(!checkPun.getState().equals(Integer.parseInt(map.get("oldState").toString()))){
                ValidateUtils.isTrue(false,ProductOrderExcption.class, "当前状态已经更新，请刷新页面再操作！");
            }
        }
        PunishScheme punishScheme = new PunishScheme();
        punishScheme.setId(id);

        if(StringUtils.isNotEmpty(map.get("punishName"))){
            punishScheme.setName(map.get("punishName").toString().trim());
        }

        if(StringUtils.isNotEmpty(map.get("introduce"))){
            ValidateUtils.isTrue(String.valueOf(map.get("introduce")).length()<=50,ProductOrderExcption.class,"方案介绍不能超过50个字！");
            punishScheme.setIntroduce(map.get("introduce").toString().trim());
        }

        if(StringUtils.isNotEmpty(map.get("state"))){
            punishScheme.setState(Integer.parseInt(map.get("state").toString()));//0初始状态 (0:未上架1:已上架2:删除)
        }
        this.updateOpt(punishScheme,sessionUser);
        punishScheme.setUpdaterOrgName(org.getName());
        punishSchemeDao.updatePunishById(punishScheme);
    }

    /**
     * @Title: 查询方案详情并跳转编辑页面
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    public void editPunish(Model model,Long id){
        List<Map> list = punishDetailDao.selectPunishDetailByPunishId(new HashMap(){{
            put("id",id);
        }});
        model.addAttribute("basicsList",list);
    }

    /**
     * @Title: 修改扣罚方明细列表
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    @Transactional
    public void editPunisDetailList(Map params){
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(sessionUser.getOrgId());
        ValidateUtils.strNotEmpty(org, ProductOrderExcption.class, "未获取到登录人部门信息！");
        ValidateUtils.strNotEmpty(params.get("punishId"), ProductOrderExcption.class, "方案ID不能为空！");
        Long punishId = Long.parseLong(params.get("punishId").toString());
        //查询方案信息
        PunishScheme punishScheme = punishSchemeDao.selectPunishById(punishId);
        ValidateUtils.strNotEmpty(punishScheme, ProductOrderExcption.class, "未查询到相关的方案信息！");
        if (!punishScheme.getState().equals(0)){
            throw new ProductOrderExcption("扣罚对应的方案不是下架状态，不能操作！");
        }

        JSONArray jsonArray = JSONArray.parseArray(params.get("params").toString());
        if(jsonArray != null && jsonArray.size()>0){
            for(int i = 0;i<jsonArray.size();i++){
                JSONObject job = jsonArray.getJSONObject(i);
                PunishDetail punishDetail = new PunishDetail();
                punishDetail.setId(Long.parseLong(job.get("id")+""));
                BigDecimal money = new BigDecimal(job.get("money")+"");
                punishDetail.setMoney(money);
                BigDecimal conductPoints = new BigDecimal(job.get("conductPoints")+"");
                punishDetail.setConductPoints(conductPoints);
                punishDetail.setVersion(Long.parseLong(job.get("version")+""));
                this.updateOpt(punishDetail,sessionUser);
                punishDetail.setUpdaterOrgName(org.getName());
                int j = punishDetailDao.updatePunishDetailById(punishDetail);
                if(j == 0){
                    throw new ProductOrderExcption("信息已经被修改过，请刷新页面后重试！");
                }
            }
        }

    }


    /**
     * @Title: 新增扣罚方案
     * @author: cuipeng
     * @creat_date: 2019/03/19
     **/
    @Transactional
    public void addPunishInfor(Map params){
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(sessionUser.getOrgId());
        ValidateUtils.strNotEmpty(org, ProductOrderExcption.class, "未获取到登录人部门信息！");
        ValidateUtils.strNotEmpty(params.get("punishId"), ProductOrderExcption.class, "方案ID不能为空！");
        ValidateUtils.strNotEmpty(params.get("teamId"), ProductOrderExcption.class, "团队不能为空！");
        ValidateUtils.strNotEmpty(params.get("conductPoints"), ProductOrderExcption.class, "操行分不能为空！");
        ValidateUtils.strNotEmpty(params.get("money"), ProductOrderExcption.class, "罚款不能为空！");
        //获取扣罚方案ID
        Long punishId = Long.parseLong(params.get("punishId").toString());
        //查询方案信息
        PunishScheme punishScheme = punishSchemeDao.selectPunishById(punishId);
        ValidateUtils.strNotEmpty(punishScheme, ProductOrderExcption.class, "未查询到相关的方案信息！");
        if (!punishScheme.getState().equals(0)){
            throw new ProductOrderExcption("扣罚对应的方案不是下架状态，不能新增！");
        }
        //查询团队是否已经存在
        List<Map> list = punishDetailDao.selectPunishDetailByPunishId(new HashMap(){{
            put("id",punishId);
            put("teamId",params.get("teamId"));
        }});
        if (list != null && list.size() > 0){
            throw new ProductOrderExcption("【"+params.get("teamName")+"】已经存在，请不要重复添加！");
        }
        PunishDetail punishDetail = new PunishDetail();
        punishDetail.setId(DggKeyWorker.nextId());
        BigDecimal conductPoints = new BigDecimal(params.get("conductPoints")+"");
        BigDecimal money = new BigDecimal(params.get("money")+"");
        punishDetail.setConductPoints(conductPoints);
        punishDetail.setMoney(money);
        punishDetail.setPunishId(punishId);
        punishDetail.setTeamId(Long.parseLong(params.get("teamId").toString()));
        punishDetail.setTeamName(params.get("teamName").toString());
        punishDetail.setFlag(1);
        punishDetail.setIsBasics(1);
        punishDetail.setVersion(0L);
        this.saveOpt(punishDetail,sessionUser);
        punishDetail.setCreaterOrgName(org.getName());
        punishDetail.setUpdaterOrgName(org.getName());
        punishDetailDao.addPunishDetail(punishDetail);

    }

    /**
     * 修改单条扣罚详情的值
     */
    @Transactional
    public void editPunishInfor(Map params){
        UserEntity sessionUser = this.sessionManager.getCurrentUser();
        ValidateUtils.strNotEmpty(sessionUser, ProductOrderExcption.class, "未获取到登陆人，请重新登录！");
        OrganizationEntity org = organizationManager.findOrgEntityByOrgId(sessionUser.getOrgId());
        ValidateUtils.strNotEmpty(org, ProductOrderExcption.class, "未获取到登录人部门信息！");
        ValidateUtils.strNotEmpty(params.get("id"), ProductOrderExcption.class, "扣罚ID不能为空！");
        ValidateUtils.strNotEmpty(params.get("punishId"), ProductOrderExcption.class, "方案ID不能为空！");

        Long punishId = Long.parseLong(params.get("punishId").toString());
        //查询方案信息
        PunishScheme punishScheme = punishSchemeDao.selectPunishById(punishId);
        ValidateUtils.strNotEmpty(punishScheme, ProductOrderExcption.class, "未查询到相关的方案信息！");
        if (!punishScheme.getState().equals(0)){
            throw new ProductOrderExcption("扣罚对应的方案不是下架状态，不能操作！");
        }

        PunishDetail punishDetail = new PunishDetail();
        punishDetail.setId(Long.parseLong(params.get("id").toString()));
        ValidateUtils.strNotEmpty(params.get("version"), ProductOrderExcption.class, "版本号不能为空！");
        punishDetail.setVersion(Long.parseLong(params.get("version")+""));
        if (StringUtils.isNotEmpty(params.get("flag"))){
            punishDetail.setFlag(Integer.parseInt(params.get("flag").toString()));
        }
        if (StringUtils.isNotEmpty(params.get("conduct_points"))){
            BigDecimal bigDecimal = new BigDecimal(params.get("conduct_points")+"");
            punishDetail.setConductPoints(bigDecimal);
        }
        if (StringUtils.isNotEmpty(params.get("money"))){
            BigDecimal bigDecimal = new BigDecimal(params.get("money")+"");
            punishDetail.setMoney(bigDecimal);
        }
        this.updateOpt(punishDetail,sessionUser);
        punishDetail.setUpdaterOrgName(org.getName());
        int i = punishDetailDao.updatePunishDetailById(punishDetail);
        if(i == 0){
            throw new ProductOrderExcption("这条信息已经被修改过，请刷新页面后重试！");
        }
    }

    /**
     * 查询所有节点超时扣罚列表数据
     */
    public List<NodeTimeOutPunish> nodeTimeoutPunish(Map params){
        if(StringUtils.isNotEmpty(params.get("timeOut"))){
            String timeOut=String.valueOf(params.get("timeOut"));
            String timeOutStart=timeOut.substring(0,timeOut.indexOf("~"));
            timeOutStart= timeOutStart.trim();
            String timeOutEnd = timeOut.substring(timeOut.indexOf("~") + 1);
            timeOutEnd= timeOutEnd.trim();
            params.put("timeOutStart", timeOutStart);
            params.put("timeOutEnd", timeOutEnd);
        }
        List<NodeTimeOutPunish> nodeTimeOutPunishList = nodeTimeOutPunishDao.queryWithPage(params);
        return nodeTimeOutPunishList;
    }

}
